<?php

namespace Modules\System\Traits;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Modules\System\Services\Mds\MDSArray;
use Modules\System\Services\Sys\Database;
use Modules\System\Services\Sys\Template;

trait Backend
{
    /**
     * 添加和编辑页面
     * http://chinadmin.top/Chinadmin/admin/Advertisement/create
     */
    public function create(Request $request){

        $i = $request->input();
        $data = $this->createData($request,$i);
        if(isset($i['MT'])){
            return view('system::admin.Form.example_create',$data);
        }else{
            if($this->class == 'Form'){
                return view('system::admin.Form.create',$data);
            }else{
                if(defined('MDS_DEFAULTS')){
                    return view(strtolower($this->Modules) . '::admin.Defaults.create',$data);
                }else{
                    return view(strtolower($this->Modules) . '::admin.' . $this->class . '.create',$data);
                }
            }
        }

    }

    /**
     * 获取本页的数据添加或者编辑
     */
    protected function createData($request,$i){

        //如果是ajax，执行ajax编辑添加数据
        if($request->ajax()){
            $this->createAjax($i);
        }

        $user = Auth::guard('admin')->user();

        $data['i'] = $i;
        $data['i_i'] = urlencode(json_encode($i));
        $data['user'] = $user;

        //如果有些编辑连接上的参数不是用的本数据库的主键，那么就赋值一个主键是id的值。
        if(!isset($i[$this->models->primaryKey])){
            $i[$this->models->primaryKey] = isset($i["id"]) ? $i["id"] : "";
        }

        //#编辑还是添加
        if(!empty($i[$this->models->primaryKey])){
            $data = $this->create_edit($data,$i);  //如果是编辑就获取编辑页面的数据
        }else{
            $data['this_data'] = [];
        }

        //获取form表的配置信息
        $data = $this->getFormInfo($data);

        //son::如果子类定义就调用子类的处理方法
        if(method_exists($this,'sonCreate')){
            $data = $this->sonCreate($data);
        }

        return $data;

    }

    /**
     * 编辑::获取本页的数据
     */
    protected function create_edit($data,$i){

        $this->with = isset($this->with) ? $this->with : [];

        //这个是调取一条信息::对象可以当数组使用
        $data['this_data_obj'] = $this->models::with($this->with)->where($this->models->primaryKey,$i[$this->models->primaryKey])->first();

        $data['this_data'] = $data['this_data_obj']->toArray();

        //form信息不进行json转数组。
        if($this->models->primaryKey == 'form_id'){
            return $data;
        }

        foreach($data['this_data'] as $ke => $ve){

            //已经是数组的不操作
            if(gettype($ve) == 'array'){
                continue;
            }

            //这里是把所有的json都处理了
            $ve = MDSArray::jsonToArray($ve);  //这里如果是json才得到数组
            $type = gettype($ve);
            if($type == 'array'){
                //放行类型
                if(key($ve) === 'type21'){
                    $data['this_data'][$ke] = $ve;
                    continue;
                }
                //说明是区间
                if(key($ve) === 'begin'){
                    unset($data['this_data'][$ke]);
                    $data['this_data'][$ke]['begin'] = $ve['begin'];
                    $data['this_data'][$ke]['end'] = $ve['end'];
                }else{
                    //开关
                    $data['this_data'][$ke] = [];
                    foreach($ve as $ko => $vo){
                        $data['this_data'][$ke]["$ko"] = true;
                    }
                }
            }
        }

        return $data;

    }

    /**
     * 提交ajax数据进行处理
     */
    protected function createAjax($i){

        //如果有默认值合并默认值
        $i = $this->mergeDefaultValue($i);

        //son::如果子类定义就调用子类的处理方法
        if(method_exists($this,'sonCreateAjaxBegin')){
            $i = $this->sonCreateAjaxBegin($i);
        }

        unset($i['file']);
        unset($i['s']);

        foreach($i as $k => $v){
            //带show的都是页面上需要展示给用户看，但是不需要存入数据库的数据
            if(strpos($k,"_show")){
                unset($i[$k]);
                continue;
            }
            $type = gettype($v);
            if($type == 'array'){                   //对数组数据进行json格式化
                $i[$k] = json_encode((object)$v);
            }
        }

        //更新或者添加
        if(empty($i[$this->models->primaryKey])){
            unset($i[$this->models->primaryKey]);
            $i['created_at'] = date("Y-m-d H:i:s");
            $re = $this->models::insertGetId($i);
        }else{
            $this->models::where($this->models->primaryKey,$i[$this->models->primaryKey])->update($i);
            $re = $i[$this->models->primaryKey];
        }

        //son::如果子类定义就调用子类的处理方法
        if(method_exists($this,'sonCreateAjaxEnd')){
            $end_re = $this->sonCreateAjaxEnd($i,$re);
        }

        mds_if_response($re);

    }

    /**
     * default默认值处理
     */
    public function mergeDefaultValue($i){
        //如果有默认值合并默认值
        if(isset($i['default'])){
            $default = MDSArray::jsonToArray(urldecode($i['default']));
            if(isset($default['default'])){
                $default = MDSArray::jsonToArray($default['default']);
                $i = array_merge($i,$default);
            }
            unset($i['default']);
        }

        return $i;
    }

    /**
     * 获取form表的配置信息
     */
    private function getFormInfo($data,$type = 1){

        //如果是form表
        if(isset($data['this_data']['form_id']) && !isset($this->isSysModels)){
            $Modules = "\Modules\\Chinadmin\Models\FormModel";
            $this->models->table = "ca_form";
        }else{
            $Modules = "\Modules\\" . ucfirst($this->Modules) . "\Models\FormModel";
        }

        //processingType
        $data['form'] = $Modules::where(function($query) use ($data){
            //只取一个字段
            if(isset($data['i']['showOneField'])){
                $query->where('form_id',$data['i']['id']);
            }else{
                $query->where('table_name',$this->models->table);
                $query->where("is_create","neq",1);
            }
        })->orderBy('sortCreate','desc')
            ->get()
            ->keyBy('form_id');

        //son::不同情况对form进行处理
        if(method_exists($this,'soncCeateForm')){
            $data = $this->soncCeateForm($data);
        }

        //对特殊数据统一处理。
        foreach($data['form'] as $k => $v){

            //图片变成数组信息
            if($v['type'] == '17'){
                if(!empty($data['this_data'])){
                    if(isset($data['this_data'][$v['field']])){
                        $data['this_data'][$v['field'] . "17"] = explode(",",$data['this_data'][$v['field']]);
                    }
                }
            }

            $data['form'][$k]['extends'] = $extends = MDSArray::jsonToArray($v['extends']);

            if(!empty($extends)){

                //5:用extends里面的type区分是否是活数据
                if(isset($extends['type']) && $extends['type'] == '5'){
                    //取数据
                    $method = $extends['method'];
                    $kv = $extends['model']::$method();
                    $data['form'][$k]['extends'] = $kv;
                }

                //18:如果是编辑再找相关信息
                if($v['type'] == '18'){

                    //多选的处理
                    if($extends['cols'][0]['type'] == "checkbox"){
                        if(isset($data['this_data'][$v['field']])){
                            $show = $extends['model']::whereIn($extends['foreignKey'],explode(",",$data['this_data'][$v['field']]))->pluck($extends['showName']);
                            if(!empty($show)){
                                $show = $show->toArray();
                            }
                            $data['this_data'][$v['field'] . "_show"] = implode(",",$show);
                        }
                    }else{
                        //进行初始赋值
                        $data['this_data'][$v['field'] . "_show"] = isset($data['this_data'][$extends['relation']][$extends['showName']]) ? $data['this_data'][$extends['relation']][$extends['showName']] : "";

                    }

                    if(isset($data['form'][$k]->extends['cols'])){
                        $data['form'][$k]['cols'] = json_encode($extends['cols']);
                    }
                }
            }
        }

        return $data;

    }

    /**------------------------------------------------------**/

    /**
     * 首页列表页
     * http://chinadmin.top/chinadmin/admin/advertisement/index
     */
    public function index(Request $request){

        $i = $request->input();

        $data = $this->indexData($i,$request);

        //d($data['form']->toArray());
        if(isset($i['MT'])){
            return view('system::admin.Form.example_index',$data);
        }else{
            if($this->class == 'Form'){
                return view('system::admin.Form.index',$data);
            }else{
                if(defined('MDS_DEFAULTS')){
                    return view(strtolower($this->Modules) . '::admin.Defaults.index',$data);
                }else{
                    return view(strtolower($this->Modules) . '::admin.' . $this->class . '.index',$data);
                }
            }
        }

    }

    /**
     * 首页列表页获取ajax数据
     */
    protected function indexData($i,$request){

        $data['i'] = $i;
        unset($i['MT']);

        //ajax请求数据
        if($request->ajax()){
            $this->indexAjax($i);
        }

        if(!empty($i)){
            unset($i['s']);
            $data['i_i'] = json_encode($i);
        }else{
            $data['i_i'] = "";
        }

        $data['ThisGet'] = "";
        foreach($i as $k => $v){
            $data['ThisGet'] = "&" . $k . "=" . $v;
        }
        if(!empty($data['ThisGet'])){
            $data['ThisGet'] = substr($data['ThisGet'],1);
        }

        //获取form配置信息
        $data = $this->getIndexForm($data);

        //子类写的逻辑
        if(method_exists($this,'sonIndex')){
            $data = $this->sonIndex($data);
        }

        if(!isset($data['formSearch'])){
            $data['formSearch'] = $data['form'];
        }

        return $data;

    }

    /**
     * 首页获取的form表单数据信息
     */
    protected function getIndexForm($data){

        $Modules = "\Modules\\" . ucfirst($this->Modules) . "\Models\FormModel";
        //d($Modules);

        //DB::connection()->enableQueryLog(); // 开启查询日志
        $data['form'] = $Modules::where(function($query) use ($data){
            //只取一个字段
            if(isset($data['i']['showOneField'])){
                $query->where('form_id',$data['i']['id']);
            }else{
                $query->where('table_name',$this->models->table);
                $query->where("display",1);
            }
        })->orderBy('sort','desc')
            ->get()
            ->keyBy('form_id');
        //d(DB::getQueryLog());

        //d($data['form']);

        //form信息存在到这里
        if((count($data['form']) == 0) && $this->models->table == 'sys_form'){
            $data['form'] = \Modules\Chinadmin\Models\FormModel::orderBy('sort','desc')
                ->get()
                ->keyBy('form_id');
        }

        //d($data['form'][182]->toArray());
        //print_r($data['form']->toArray());exit;
        //页面加载的时候根据类型取数据做相应的展示
        foreach($data['form'] as $k => $v){

            //配置信息 数组话
            if(!empty($v->extends)){
                $extends_array = $data['form'][$k]->extends_array = MDSArray::jsonToArray($v->extends);
            }

            //这里针对需要的不同类型type(编辑的展现形式)进行处理
            switch($v['type']){
                case 5: //下拉
                    if(isset($extends_array['type'])){
                        if($extends_array['type'] == 5){
                            $method = $extends_array['method'];
                            $data['form'][$k]->extends = $extends_array['model']::$method();
                        }
                    }else{
                        $data['form'][$k]->extends = $v->extends;
                    }
                    break;
                case 13: //单选
                    //$data['form'][$k]->extends_kv13 = json_encode(array_column($data['form'][$k]->extends_array,"title","default"));
                    break;
                default:
            }

            //不同的搜索类型进行处理
            switch($v['search_type']){
                case 3:
                    $method = $v->search_extend['method'];
                    $data['form'][$k]->option3 = $v->search_extend['model']::$method(1);
                    $data['form'][$k]->option3 = MDSArray::jsonToArray($data['form'][$k]->option3);
                    break;
                default:
            }

        }

        return $data;

    }

    public function indexAjax($i){

        $this->with = $this->with ?? [];
        if(gettype($this->with) == 'string'){
            $this->with = [$this->with];
        }
        if(isset($i['with'])){
            $i['with'] = explode(",",$i['with']);
            $this->with = array_merge($this->with,$i['with']);
        }

        //如果子类定义就调用子类的处理方法
        if(method_exists($this,'sonIndexAjaxBegin')){
            $i = $this->sonIndexAjaxBegin($i);
        }

        unset($i['s']);

        if(empty($i['page'])){
            $i['page'] = 1;
        }

        $start = ($i['page'] - 1) * $i['limit'];
        $end = $i['limit'];

        //组合构造条件的构造,因为这个条件会直接加到第一层上。
        if(isset($i['searchType'])){
            unset($i['searchType']);
            unset($i['page']);
            unset($i['limit']);

            foreach($i as $k => $v){
                unset($i[$k]);
                $i["where_like_" . $k] = $v;
            }
        }


        $i = Database::transformation($i);     //构造条件和排序
        list($where) = $this->buildparams($i); //执行条件

        //DB::connection()->enableQueryLog(); // 开启查询日志
        $data = $this->models::with($this->with)
            ->where($where)
            ->when($i['orderBy'] ?? false,function($query,$sortV){
                foreach($sortV as $k => $v){
                    $query->orderBy($v['field'],$v['sort']);
                }
            },function($query){
                return $query->orderBy($this->models->primaryKey,"desc");
            })
            ->offset($start)
            ->limit($end)
            ->get();
        //d(DB::getQueryLog());

        $count = $this->models::where($where)->count();
        mdsResponse(0,"获取成功",$data,['count' => $count]);

    }

    /**
     * 搜索条件
     */
    public function buildparams($i){

        $where = function($query) use ($i){

            //搜索条件::列表页上的搜索项
            if(isset($i['searchParams'])){

                $searchParams = MDSArray::jsonToArray($i['searchParams']);

                foreach($searchParams as $ks => $vs){

                    //时间区间
                    if(isset($vs['begin'])){

                        if(empty($vs['begin']['val']) && empty($vs['end']['val'])){
                            //mdsResponse(400,"开始时间结束时间必须选一个");
                            continue;
                        }

                        if(empty($vs['begin']['val'])){
                            $query->where($ks,"<",$vs['end']['val']);
                        }

                        if(empty($vs['end']['val'])){
                            $query->where($ks,">",$vs['begin']['val']);
                        }

                        $query->whereBetween($ks,[$vs['begin']['val'],$vs['end']['val']]);

                    }

                    //空-1不搜索
                    if(!isset($vs['val']) || $vs['val'] == -1 || $vs['val'] == ''){
                        continue;
                    }
                    //like
                    if($vs['search'] == 'like'){
                        $query->where($ks,$vs['search'],"%" . $vs['val'] . "%");
                    }
                    //等于
                    if($vs['search'] == '=' && $vs['search'] != ''){
                        $query->where($ks,$vs['val']);
                    }

                }

            }

            //页面链接上面的条件
            Database::splicingWhere($i,$query);

        };
        return [$where];

    }

    /**------------------------------------------------------**/

    /**
     * 删除
     * http://chinadmin.top/chinadmin/admin/advertisement/delete
     */
    public function delete(Request $request){

        $i = $request->input();
        if(isset($i['datac'])){

            //批量删除
            if(empty($i['datac'])){
                mdsResponse("400","您没有选中任何数据");
            }

            $chestnut_id_arr = array_column($i['datac'],$this->models->primaryKey);

            if($this->models->primaryKey == 'employee_id'){
                if(in_array(1,$chestnut_id_arr)){
                    mdsResponse("400","1号员工不可以删除");
                }
            }

            $if = $this->models::whereIn($this->models->primaryKey,$chestnut_id_arr)->delete();

        }else{

            if($this->models->primaryKey == 'employee_id'){
                if($i['id'] == 1){
                    mdsResponse("400","1号员工不可以删除");
                }
            }

            //删除单个
            if(empty($i['id'])){
                mdsResponse(400,"系统错误del");
            }

            $if = $this->models::where($this->models->primaryKey,$i['id'])->delete();
        }
        //如果子类定义就调用子类的处理方法
        if(method_exists($this,'sonDel')){
            $data = $this->sonDel($i);
        }
        mds_if_response($if);

    }

    /**------------------------------------------------------**/

    /**
     * 根据id获取本模型一条信息，统一用。
     * http://chinadmin.top/chinadmin/admin/advertisement/getOne
     */
    public function getOne(Request $request){

        $i = $request->input();
        if(!isset($i[$this->models->primaryKey])){
            mdsResponse(400,"需要传入正确的id");
        }
        $re = $this->models::with($this->with)->where([$this->models->primaryKey => $i[$this->models->primaryKey]])->first();
        mdsResponse(200,"数据",$re);

    }

    /**------------------------------------------------------**/

    /**
     * 根据id获取本模型多条数据
     * http://chinadmin.top/chinadmin/admin/advertisement/getList
     */
    public function getList(Request $request){

        $i = $request->input();
        if(!isset($i['where'])){
            mdsResponse(400,"需要传入where");
        }

        //这里是整理搜索条件
        $i = Database::transformation($i['where']);
        list($where) = $this->buildparams($i);
        $re = $this->models::with($this->with)
            ->where($where)
            ->get();

        mdsResponse(200,"数据",$re);

    }

}
